package com.shanghaionstar.user.service;

import android.content.Context;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.onstar.cn.api.PublicService;
import com.onstar.cn.common.exception.OnStarException;
import com.onstar.cn.common.util.CommonUtil;
import com.onstar.cn.common.util.Constants;
import com.onstar.cn.common.util.DeviceUtil;
import com.onstar.cn.common.util.PreferencesUtls;
import com.onstar.cn.framework.annotation.http.HeadsValue;
import com.onstar.cn.framework.annotation.http.Request;
import com.onstar.cn.framework.mvp.base.core.BaseService;
import com.onstar.cn.framework.network.HttpInjectUtils;
import com.onstar.cn.framework.network.entity.RequestEntity;
import com.onstar.cn.framework.network.enumtype.HttpAccept;
import com.onstar.cn.framework.network.enumtype.HttpMethod;
import com.onstar.cn.framework.network.enumtype.Language;
import com.onstar.cn.mag.enumtype.OSType;
import com.onstar.cn.mag.publicService.response.BroadcastEntity;
import com.onstar.cn.more.response.BroadcastResponseEntity;
import com.onstar.cn.sqlite.entities.BroadcastHeaderEntity;
import com.onstar.cn.sqlite.xutil.db.sqlite.Selector;
import com.onstar.cn.sqlite.xutil.exception.DbException;
import com.shanghaionstar.OnstarApplication;
import com.shanghaionstar.sqlite.BroadcastHeaderService;
import com.shanghaionstar.utils.ApplicationUtil;
import com.shanghaionstar.utils.BusinessUtil;
import com.shanghaionstar.utils.FinalConfigParams;
import com.shanghaionstar.utils.NetConnectUtil;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import rx.Observable;
import rx.functions.Func0;

/**
 * Created by Yonglang Hong on 2016/8/9.
 */
public class BroadcastService extends BaseService {

    private Context context;

    private BroadcastHeaderService headerService;

    public BroadcastService(Context context) {
        this.context = context;
        headerService = new BroadcastHeaderService(context);
    }

    @Override
    public RequestEntity getRequestEntity() {
        return null;
    }

    @Override
    public Object jsonToBean(String json) {
        return null;
    }

    public Observable<String> loadMsgList() {
        return Observable.defer(new Func0<Observable<String>>() {
            @Override
            public Observable<String> call() {
                try {
                    return Observable.just(doLoadMsgList());
                } catch (OnStarException e) {
                    return Observable.error(e);
                }
            }
        });
    }

    public Observable<List<BroadcastHeaderEntity>> getAllListFromDB() {
        return Observable.defer(new Func0<Observable<List<BroadcastHeaderEntity>>>() {
            @Override
            public Observable<List<BroadcastHeaderEntity>> call() {
                try {
                    return Observable.just(doGetAllListFromDB());
                } catch (Exception e) {
                    return Observable.error(e);
                }
            }
        });
    }

    @Request(heads = @HeadsValue(accept = HttpAccept.JSON, language = Language.AUTO), method = HttpMethod.PUT)
    public String doLoadMsgList() throws OnStarException {
        String vin = "123";
        if (!CommonUtil.isNull(ApplicationUtil.getInstance().getVin()))
            vin = ApplicationUtil.getInstance().getCurrentVehicle().getVin();
        PublicService service = new PublicService(Constants.CURRENT_SERVER_URL);
        RequestEntity requestEntity = NetConnectUtil.getAuthRequestEntity(context);
        BroadcastEntity broadcastEntity = new BroadcastEntity();
        broadcastEntity.setOsType(OSType.ANDROID_SMALL.toString());
        broadcastEntity.setVin(vin);
        if (!CommonUtil.isNull(ApplicationUtil.getInstance().getCurrentVehicle())) {
            broadcastEntity.setYear(ApplicationUtil.getInstance().getCurrentVehicle().getYear());
            broadcastEntity.setModel(ApplicationUtil.getInstance().getCurrentVehicle().getModel());
        }
        service.broadcast(requestEntity, broadcastEntity);

        requestEntity = HttpInjectUtils.injectHttp(getClass(), "doLoadMsgList", requestEntity);
        String response = NetConnectUtil.getResponse(getDatas(requestEntity));
        if (!response.equals("[]")) {
            List<BroadcastResponseEntity> resultList = new Gson().fromJson( response,new TypeToken<ArrayList<BroadcastResponseEntity>>(){}.getType());
            handleResult(resultList, vin);
        } else {
            headerService.deleteExpireFile(new ArrayList<BroadcastHeaderEntity>(), vin);// 删除
        }
        return response;
    }

    public void handleResult(List<BroadcastResponseEntity> resultList, String vin) {
        long id = -1;
        List<BroadcastHeaderEntity> headers = new ArrayList<>();
        if (resultList != null && resultList.size() > 0) {
            for (BroadcastResponseEntity entity : resultList) {
                BroadcastHeaderEntity headerEntity = new BroadcastHeaderEntity();
                headerEntity.setBroadcastId(entity.getId());
                headerEntity.setContent(entity.getContent());
                headerEntity.setCreateDate(new Date().getTime() + "");
                headerEntity.setLanguage(DeviceUtil.getLanguage());
                headerEntity.setModelNumber(entity.getModel());
                headerEntity.setPublishTime(entity.getPublishTimestamp());
                headerEntity.setTitle(entity.getTitle());
                headerEntity.setVin(vin);
                headers.add(headerEntity);
                try {
                    String idStr = entity.getId();
                    id = Math.max(Long.parseLong(idStr), id);
                } catch (NumberFormatException expected) {
                }
            }
            long curId = PreferencesUtls.getInstance(context).getLong(FinalConfigParams.BROADCAST_LAST_ID, -1L);
            PreferencesUtls.getInstance(context).putLong(FinalConfigParams.BROADCAST_LAST_ID, Math.max(curId, id));
            headerService.insert(headers, vin);// 添加到数据库
        } else {
            headerService.deleteExpireFile(new ArrayList<BroadcastHeaderEntity>(), vin);// 删除
        }
        List<BroadcastHeaderEntity> list = headerService.getAllBroadcastHeader(vin, FinalConfigParams.FALSE);
        String broadCount;
        if (list.size() > 99)
            broadCount = list.size() > 99 ? "99" : "";
        else
            broadCount = list.size() > 0 ? list.size() + "" : "";
        OnstarApplication onstarApplication = (OnstarApplication) context.getApplicationContext();
        onstarApplication.setBrocastCount(broadCount);
        long curId = PreferencesUtls.getInstance(context).getLong(FinalConfigParams.BROADCAST_LAST_ID, -1L);
        setBroadcastUnread(id, curId);
        headerService.insert(headers, vin);// 添加到数据库
    }

    private void setBroadcastUnread(long id, long curId) {
        if (curId < id) {
            PreferencesUtls.getInstance(context).putString(FinalConfigParams.BROADCAST_UNREAD, FinalConfigParams.TRUE);
        } else {
            PreferencesUtls.getInstance(context).putString(FinalConfigParams.BROADCAST_UNREAD, FinalConfigParams.FALSE);
        }
    }

    private List<BroadcastHeaderEntity> doGetAllListFromDB() {
        String vin = "123";
        if (!CommonUtil.isNull(ApplicationUtil.getInstance().getVin()))
            vin = ApplicationUtil.getInstance().getCurrentVehicle().getVin();
        List<BroadcastHeaderEntity> msglist = null;
        try {
            msglist = OnstarApplication.getmDbUtils()
                    .findAll(Selector.from(BroadcastHeaderEntity.class).where("vin","=",vin).orderBy("publishTime",true));
        } catch (DbException e) {
            e.printStackTrace();
        }
//                headerService.getAll(null, "vin=?", new String[]{vin}, null, null,
//                "publishTime desc", null);// 查询所有消息
        msglist = sortList(msglist);
        return msglist;
    }

    private List<BroadcastHeaderEntity> sortList(List<BroadcastHeaderEntity> rawList) {
        List<BroadcastHeaderEntity> tempList = new ArrayList<BroadcastHeaderEntity>();
        for (int i = 0; i < rawList.size(); i++) {
            BroadcastHeaderEntity entity = rawList.get(i);
            if (FinalConfigParams.FALSE.equals(entity.getIsRead())) {
                tempList.add(entity);
            }
        }
        rawList.removeAll(tempList);
        tempList.addAll(rawList);
        rawList.clear();
        return tempList;
    }

    public void update(BroadcastHeaderEntity headerEntity) {
        headerService.update(headerEntity);
    }

}
